package task

import (
	"strings"

	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/ws"

	"ssdevice/common/constant"
	"ssdevice/common/cron"
	"ssdevice/internal/device/models"
	"ssdevice/internal/device/service"
)

func Start() {
	// 刷新ws客户端权限
	cron.AddCronTask("0 0/5 * * * ?", refreshWsClientAuth, false)
	//定时清理超时设备任务
	service.StartCheckTask()
	// 刷新model-protocol缓存(因为可以手动改表)
	cron.AddCronTask("0/15 * * * * ?", refreshPdModelProto, false)
}

func refreshWsClientAuth() {
	if ws.GetClientLen() == 0 {
		return
	}
	keys := env.Cache.ScanKey("login_user:*")
	if len(keys) == 0 {
		return
	}
	uidMapInfo := make(map[string]ws.ClientAuth)
	for _, key := range keys {
		userInfo, _ := env.Cache.HashGetAll(key)
		uid := userInfo[constant.JwtKeyUserId]
		cauth := ws.ClientAuth{
			UserId:     uid,
			DeptIdList: strings.Split(userInfo[constant.JwtKeyUserDeptIds], ","),
		}
		if uid == "1" {
			cauth.AgencyId = "1"
		} else {
			cauth.AgencyId = userInfo[constant.JwtKeyAgencyId]
		}
		uidMapInfo[uid] = cauth
	}
	ws.AuthInfoRefresh(uidMapInfo)
}

func refreshPdModelProto() {
	sysProtocol := models.SysProtocol{}
	m := sysProtocol.FindGateModelMap(env.Db)
	for md, protocol := range m {
		if protocol.Value == nil {
			continue
		}
		constant.ModelProtocolCache.Set(md, *protocol.Value)
	}
}
